package com.rcklos.NettyLentMe.match;

import com.rcklos.NettyLentMe.ServerConfig;
import com.rcklos.NettyLentMe.ServerTransponder;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;

public class MatchContainer implements MatchContainerInterface{
    public static MatchContainer instance = new MatchContainer();
    public static MatchContainer getInstance() {
        return instance;
    }
    private MatchContainer(){}

    /**
     * String userid
     * String token
     */
    private Map<String,String> queue = new ConcurrentHashMap<String, String>();
    Random random = new Random();

    @Override
    public void addQueueByUserId(String userId,String time) {
        if ( !queue.containsKey(userId) ) queue.put(userId,"");
//        else {
//            if ( !time.equals("0") ) return;
//        }
        if ( queue.get(userId).isEmpty() ){
            for ( Map.Entry<String,String> entry : queue.entrySet() ){
                if ( !entry.getKey().equals(userId) && entry.getValue().isEmpty() ){
                    //主动匹配成功
                    System.out.println(userId+"主动匹配成功");
                    String token = genToken();//在这里生成token
                    queue.put(userId,token);
                    entry.setValue(token);
                    ServerTransponder.getInstance().sendMsg(
                            //匹配成功是1000
                            ServerTransponder.getInstance().genMsg(ServerConfig.typeMatch,null,userId,"1000",token)
                    );
                    // 顺便校准时间
                    ServerTransponder.getInstance().sendStringSingleChatTime(userId);
                    return;
                }
            }
        } else {
            //被动匹配成功
            System.out.println(userId+"被动匹配成功");
            String token = queue.get(userId);//获取相同的token
            ServerTransponder.getInstance().sendMsg(
                    //匹配成功是1000
                    ServerTransponder.getInstance().genMsg(ServerConfig.typeMatch,null,userId,"1000",token)
            );
            // 顺便校准时间
            ServerTransponder.getInstance().sendStringSingleChatTime(userId);
            return;
        }
        ServerTransponder.getInstance().sendMsg(
                //匹配失败
                ServerTransponder.getInstance().genMsg(ServerConfig.typeMatch,null,userId,time,null)
        );
    }

    @Override
    public String genToken() {
        int randInt = random.nextInt(1000)+1000;
        String token = String.format("token_%d:%d",randInt,System.currentTimeMillis());
        return token;
    }

    @Override
    public long getTimeMillisFromToken(String token) {
        String timeMillisString = token.split(":")[1];
        if ( timeMillisString == null || timeMillisString.isEmpty() ){
            return 0;
        }
        long timeMillis = Long.valueOf(timeMillisString);
        return timeMillis;
    }

    @Override
    public String genToken(List<String> users) {
        //群聊token
        //暂时闲置，待拓展
        return null;
    }

    @Override
    public String getUserByToken(String token, String exceptUserid) {
        for ( Map.Entry<String,String> entry : queue.entrySet() ){
            if ( !entry.getKey().equals(exceptUserid) && entry.getValue().equals(token) ){
                return entry.getKey();
            }
        }
        return null;
    }

    @Override
    public List<String> getUsersByToken(String token) {
        List<String> array = new ArrayList<String>();
        for ( Map.Entry<String,String> entry : queue.entrySet() ){
            if ( entry.getValue().equals(token) ){
                array.add(entry.getKey());
            }
        }
        return array;
    }

    @Override
    public String getTokenByUserid(String userid) {
        if ( queue.containsKey(userid) ){
            return queue.get(userid);
        }
        return null;
    }

    @Override
    public void removeTokenByUserid(String userid) {
        if ( queue.containsKey(userid) ) {
            String token = queue.get(userid);
            for ( Map.Entry<String,String> entry : queue.entrySet() ){
                if ( entry.getValue().equals(token) ){
                    ServerTransponder.getInstance().sendInformTheSingleTokenDestroy(entry.getKey());
                    System.out.println("用户["+entry.getKey()+"]已于MatchContainer移除");
                    queue.remove(entry.getKey());
                }
            }
        }
    }

    @Override
    public boolean isQueueContainsUserAndContainsToken( String userid ){
        if ( queue.containsKey(userid) ){
            if ( queue.get(userid) != null && !queue.get(userid).isEmpty() ){
                return true;
            }
        }
        return false;
    }
}
